package com.qf.business.message.handler;

import com.alibaba.fastjson.JSON;
import com.qf.business.course.feign.CourseFeign;
import com.qf.business.message.entity.Message;
import com.qf.business.message.entity.Rooms;
import com.qf.business.message.entity.User;
import com.qf.business.message.handler.base.BaseMsgChannelHandler;
import com.qf.business.message.utils.RoomUtils;
import com.qf.commons.core.utils.JwtUtils;
import com.qf.data.user.entity.Student;
import com.qf.data.user.entity.Teacher;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.kurento.client.KurentoClient;
import org.kurento.client.WebRtcEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 主播方 和 观看者 注册到信令服务器的消息处理
 * author Ken
 * create_time 2023/1/6
 */
@Component
@ChannelHandler.Sharable
public class BaseRegisterMsgChannelHandler extends BaseMsgChannelHandler {

    @Autowired
    private KurentoClient kurentoClient;

    @Autowired
    private CourseFeign courseFeign;

    @Override
    protected String action() {
        return "register";
    }

    @Override
    protected void handler(ChannelHandlerContext ctx, Message msg) {
        //获取相关的参数
        String role = msg.getRole();
        Long cid = msg.getCid();
        String cname = msg.getCname();
        String token = msg.getToken();

        //解析获取用户的身份信息 - json
        String userJson = (String) JwtUtils.parseJwtToken(token, "user");
        if (userJson == null) {
            //身份校验失败
            Message message = new Message()
                    .setAction("authError");
            ctx.writeAndFlush(message);
            return;
        }

        //用户id
        Long uid;
        //用户名称
        String name;
        //用户头像
        String header;

        if (role.equals("master")) {
            //主播 - 教师端
            Teacher teacher = JSON.parseObject(userJson, Teacher.class);
            uid = teacher.getId();
            name = teacher.getName();
            header = teacher.getHeader();
        } else {
            //观看者 - 学生端
            Student student = JSON.parseObject(userJson, Student.class);
            uid = student.getId();
            name = student.getNickName();
            header = student.getHeader();
        }

        //获取当前的房间
        Rooms rooms = RoomUtils.getRooms(cid, cname);

        //创建当前用户的端点
        WebRtcEndpoint userWebRtcEndPoint = new WebRtcEndpoint.Builder(rooms.getMediaPipeline()).build();

        //封装用户的身份信息
        User user = new User()
                .setUid(uid)
                .setName(name)
                .setHeader(header)
                .setRole(role)
                .setChannel(ctx.channel())
                .setWebRtcEndpoint(userWebRtcEndPoint);

        //添加到房间中
        rooms.addUser(user);

        //如果当前是主播的话，则将当前课程的状态改成已经上课
        if (role.equals("master")) {
            //将对应课程的状态 改成已经上课
            courseFeign.updateCourseStatus(cid, 1);
        } else {
            //如果是观看者，则通知所有端，更新在线人数
            Message result = new Message()
                    .setAction("number")
                    .setMsg(rooms.getSlaves().size());
            rooms.sendMsgAll(result, true);
        }

        //回复注册的结果
        Message result = new Message()
                .setAction("registerSucc")
                .setMsg(rooms.getCname());
        ctx.writeAndFlush(result);
    }
}
